﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using WebeTerm.DbBusiness;
using WebeTerm.PlugIns;
using System.Reflection;

namespace WebeTerm.Web.AjaxHandler
{
    /// <summary>
    /// Summary description for ExecutePlugIn
    /// </summary>
    public class ExecutePlugIn : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string PlugInId = context.Request["PlugInId"];
            var plugInInfo = new CompanyPlugInsBLL().All().Where(l => l.Id == new Guid(PlugInId))
                .Join(new ConfigurationInfoBLL().All(), l => l.ConfigId, r => r.Id, (l, r) => new
                {
                    l.PlugInCode,
                    l.PlugInJSon,
                    l.CompayId,
                    r.ConfigAddress,
                    ConfigId = r.Id,
                    r.ConfigPort,
                    r.ConfigRID,
                    r.ConfigSID,
                    r.ConfigType,
                    r.ConfigUserName,
                    r.ConfigUserPassword,
                    r.SiText,
                    CompanyPlugInId =  l.Id
                })
                .Join(new PlugInsBLL().All(), l => l.PlugInCode, r => r.PlugInCode, (l, r) => new {
                    l.PlugInCode,
                    l.PlugInJSon,
                    l.CompayId,
                    l.ConfigAddress,
                    l.ConfigId,
                    l.ConfigPort,
                    l.ConfigRID,
                    l.ConfigSID,
                    l.ConfigType,
                    l.ConfigUserName,
                    l.ConfigUserPassword,
                    l.SiText,
                    l.CompanyPlugInId,
                    r.IsPublic,
                    r.IsValid,
                    r.PlugInAssembly,
                    r.PlugInName
                })
                .FirstOrDefault();
            var PlugInAssembly = plugInInfo.PlugInAssembly.Split(new char[] {',' }, StringSplitOptions.RemoveEmptyEntries);
            Assembly ass = Assembly.Load(PlugInAssembly[0]);
            var plugIn =Activator.CreateInstance( ass.GetType(PlugInAssembly[1]));
            //var PlugInExecute = (plugIn as BasePlugIn<BasePlugInResult,BasePlugInConfig>);
                //.Connect(eTerm.NetSocket.SocketConnectType.User350,plugInInfo.ConfigAddress,plugInInfo.ConfigPort,plu
            context.Response.Write(jss.Serialize(plugInInfo));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}